<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import FileUpload from "@/components/file-system/file-upload.vue";
import type { FormDescChild } from "@/components/form-desc/form-desc.vue";
import { enclosureParkBarriersSaveOrUpdateUsingPost } from "@/genapi/wh-yqd";
import { useAsync } from "@/hooks/use-async";
import FileOtherUpload from "@/components/file-system/file-otherUpload.vue";
import { ref } from "vue";
import {
	getEnumOptionsField,
	GATE_STATUS_OPTIONS,
	RECORD_TYPE_OPTIONS,
} from "@/config/enum-options";

import { injectState } from "../state";

defineOptions({ name: "DetailDialog" });

const img = import.meta.glob("./assets/*.png", {
	import: "default",
	eager: true,
});

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"download" | "write" | "read">();

const beforeClose = async () => {
	if (type.value === "write") {
		await ElMessageBox.confirm("确认关闭？");
	}
};

const trigger = async (
	_type: "download" | "write" | "read",
	value = {} as any,
) => {
	type.value = _type;
	model.value = JSON.parse(JSON.stringify(value)) as any;

	await dialogRef.value?.open();
};

defineExpose({
	trigger,
});

const model = ref<(typeof page.records.value)[0]>({});
const value = ref("");

const file = computed({
	get() {
		if (model.value.fileId) {
			return [
				{
					id: model.value.fileId,
					name: model.value.fileName,
				},
			];
		}
	},
	set(value: any) {
		model.value.fileId = value?.[0]?.id;
	},
});

const title = computed(() => {
	if (type.value === "write") {
		return model.value.id ? "编辑" : "新建";
	} else {
		return `详情`;
	}
});

const { execute, isLoading } = useAsync(async () => {
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
	});

	await enclosureParkBarriersSaveOrUpdateUsingPost({
		data: {
			...model.value,
		},
	});
	ElMessage.success("提交成功");
	page.execute();
	dialogRef.value?.complete();
});
const selectOptions = ref([{ label: "员工", value: "1" }]);

function getCurrentDate(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, "0");
	const day = String(now.getDate()).padStart(2, "0");

	return `${year}-${month}-${day}`;
}
model.value.time = getCurrentDate();
const children: FormDescChild[] = [
	{
		label: "考试名称",
		prop: "name",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.name} placeholder="请输入" />
		),
		descItem: () => `${model.value.name ?? "-"}`,
	},
	{
		label: "考试类型",
		prop: "status",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-select-v2
				v-model={model.value.status}
				options={GATE_STATUS_OPTIONS}
				clearable
				placeholder="请选择类型"
			/>
		),
		descItem: () =>
			getEnumOptionsField(GATE_STATUS_OPTIONS, "label", model.value.status) ??
			"-",
	},
	{
		label: "总分数",
		prop: "number",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.number} placeholder="请输入" />
		),
		descItem: () => `${model.value.number ?? "-"}`,
	},
	{
		label: "及格分",
		prop: "location",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.location} placeholder="请输入" />
		),
		descItem: () => `${model.value.location ?? "-"}`,
	},
	{
		label: "考试时长（分钟）",
		prop: "coordinate",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.coordinate} placeholder="请输入" />
		),
		descItem: () => `${model.value.coordinate ?? "-"}`,
	},
	{
		label: "考试期限",
		prop: "applyDate",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-date-picker
				v-model={model.value.applyDate}
				clearable
				type="date"
				placeholder="安装时间"
				value-format="YYYY-MM-DD"
			/>
		),
		descItem: () => `${model.value.applyDate ?? "-"}`,
	},
];

interface Option {
	key: number;
	label: string;
	initial: string;
}

const generateData = () => {
	const data: Option[] = [];
	const states = [
		"California",
		"Illinois",
		"Maryland",
		"Texas",
		"Florida",
		"Colorado",
		"Connecticut ",
	];
	const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
	states.forEach((city, index) => {
		data.push({
			label: city,
			key: index,
			initial: initials[index],
		});
	});
	return data;
};

const data = ref<Option[]>(generateData());
const value1 = ref([]);

const filterMethod = (query, item) => {
	return item.initial.toLowerCase().includes(query.toLowerCase());
};

const tableData = ref([
	{
		name: "",
		singleNum: 0,
		singleScore: 0,
		multiNum: 0,
		multiScore: 0,
		judgeNum: 0,
		judgeScore: 0,
	},
]);

/** 鼠标移入cell */
const handleCellEnter = (row, column, cell, event) => {
	row.isEdit = true;
};

/** 鼠标移出cell */
const handleCellLeave = (row, column, cell, event) => {
	row.isEdit = false;
};

const sumScore = computed(() => {
	let sum = 0;
	tableData.value.forEach((item) => {
		sum +=
			item.singleScore * item.singleNum +
			item.multiScore * item.multiNum +
			item.judgeScore * item.judgeNum;
	});
	return sum;
});

const addRow = () => {
	tableData.value.push({
		name: "",
		singleNum: 0,
		singleScore: 0,
		multiNum: 0,
		multiScore: 0,
		judgeNum: 0,
		judgeScore: 0,
	});
};

const removeRow = (scope) => {
	tableData.value.splice(scope.$index, 1);
};
</script>

<template>
	<PromiseDialog
		ref="dialogRef"
		:title="title"
		:before-close="beforeClose"
		w="1200px!"
	>
		<el-scrollbar style="height: 508px">
			<div>
				<div
					style="
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
						height: 40px;
					"
				>
					<el-button size="small" type="primary" @click="addRow"
						>添加</el-button
					>
					<span>试卷总分：{{ sumScore }}分</span>
				</div>
				<el-table
					:data="tableData"
					size="small"
					style="width: 100%"
					@cell-mouse-enter="handleCellEnter"
					@cell-mouse-leave="handleCellLeave"
					show-overflow-tooltip
				>
					<el-table-column prop="name" label="题库名称">
						<template #default="scope">
							{{ scope.row.name === "" ? scope.row.name : "--" }}
						</template>
					</el-table-column>
					<el-table-column prop="singleNum" label="单选数量" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.singleNum"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.singleNum }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="singleScore" label="单选分数" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.singleScore"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.singleScore }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="multiNum" label="多选数量" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.multiNum"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.multiNum }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="multiScore" label="多选分数" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.multiScore"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.multiScore }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="judgeNum" label="判断题数量" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.judgeNum"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.judgeNum }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="judgeScore" label="判断题分数" width="100">
						<template #default="scope">
							<el-input
								v-if="scope.row.isEdit"
								type="number"
								class="cellItem"
								size="small"
								v-model="scope.row.judgeScore"
								placeholder="请输入"
							></el-input>
							<div v-else class="txt">{{ scope.row.judgeScore }}</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="80" v-if="tableData.length > 1">
						<template #default="scope">
							<el-button type="text" @click="removeRow(scope)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<FormDesc
				ref="formDescRef"
				m="t-24px x-30px"
				:type="type === 'read' ? 'desc' : 'form'"
				form-class="gap-x-20px"
				:model="model"
				:children="children"
				:column="2"
			/>
		</el-scrollbar>
		<template v-if="type === 'write'" #footer>
			<el-button @click="dialogRef?.close()">取消</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>确定</el-button
			>
		</template>
		<template v-else-if="type === 'read'" #footer>
			<el-button @click="dialogRef?.close()">拒绝</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>通过</el-button
			>
		</template>
	</PromiseDialog>
</template>

<style lang="scss" scoped>
.trainingListBox {
	width: 100%;
	padding: 0px 30px;

	.listBoxTitle {
		height: 50px;
		width: 100%;
		display: flex;
		align-items: center;
	}
}
.item {
	width: 100px;
	/* 调整elementUI中样式 如果不需要调整请忽略 */
	.el-input__inner {
		height: 24px !important;
	}
}
.txt {
	line-height: 24px;
	padding: 0 9px;
	box-sizing: border-box;
}
</style>
